//
//  TravelsViewController.m
//  哎游
//
//  Created by 康守帅 on 15-1-4.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TravelsListViewController.h"
#import "TravelsListTableViewCell.h"
#import "ConnectModel.h"
#import "TravelsListModel.h"
#import "macro.h"
#import "UIScrollView+MJRefresh.h"
#import "TravelsDetailViewController.h"
#import "LocationViewController.h"
#import "UIImageView+WebCache.h"
#import "WebColor.h"

@interface TravelsListViewController ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation TravelsListViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tableArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.temp = 19;
    self.navigationController.navigationBar.translucent = NO;
    if (IOS_VERSION >= 7.0) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 100)];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    label.text = @"游记";
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [WebColor linen];
    self.navigationItem.titleView = label;
    [self startJson];
    [self createTableView];
    [self SetUpRefresh];
   
}

- (void)startJson
{
    [ConnectModel connectModelWithUrlStr:@"http://api.breadtrip.com/trips/hot/?count=19&is_ipad=1&start=0" parmaters:nil finished:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *array = [dic objectForKey:@"trips"];
        for (NSDictionary *dic1 in array) {
            TravelsListModel *model = [[TravelsListModel alloc] init];
            model.ID = [dic1 objectForKey:@"id"];
            [model setValuesForKeysWithDictionary:dic1];
            [_tableArray addObject:model];
            [model release];
        }
        [_tableView reloadData];
    }];
    
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 113) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[TravelsListTableViewCell class] forCellReuseIdentifier:@"cell"];
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [_tableView registerClass:[TravelsListTableViewCell class] forCellReuseIdentifier:@"cell"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cell";
    
    TravelsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[TravelsListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    TravelsListModel *model = [_tableArray objectAtIndex:indexPath.row];
    [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_image_default] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    cell.title.text = model.name;

    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[model.first_day intValue]];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:confromTimesp];
    NSDate *localeDate = [confromTimesp  dateByAddingTimeInterval: interval];
    
    NSInteger timeOffset = [zone secondsFromGMTForDate:localeDate];
    
    NSDate *newDate = [localeDate dateByAddingTimeInterval:timeOffset];
    
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy.MM.dd"];
    NSString *dateStr = [dateFormat stringFromDate: newDate];
    cell.date.text = dateStr;
    cell.dateNum.text = [model.day_count stringValue];
    cell.visits.text = [model.view_count stringValue];
    cell.address.text = model.popular_place_str;

    [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:[model.user objectForKey:@"avatar_s"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    
    TravelsDetailViewController *travels = [[TravelsDetailViewController alloc] init];
    travels.imageUser = [model.user objectForKey:@"avatar_s"];//给detil传值
    
    cell.userName.text = [model.user objectForKey:@"name"];

    [dateFormat release];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 230;
}

// 上拉加载, 下拉刷新
- (void)SetUpRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // #warning 自动刷新(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    //2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    if ([self.tableArray count] < 100) {
        [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    }
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开立即刷新了";
    self.tableView.headerRefreshingText = @"正在刷新中";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开立即加载更多数据";
    self.tableView.footerRefreshingText = @"正在加载中";
}

- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}


- (void)footerRereshing
{
    if ([self.tableArray count] > 100) {
        [self.tableView footerEndRefreshing];
    } else {
//        self.urlModel.page += 1;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/hot/?count=18&is_ipad=1&start=%ld", (long)_temp];
            [self startJson:str];
            _temp += 18;
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
        });
    
    }
    
}

- (void)startJson:(NSString *)urlStr
{
    [ConnectModel connectModelWithUrlStr:urlStr parmaters:nil finished:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *array = [dic objectForKey:@"trips"];
        for (NSDictionary *dic1 in array) {
            TravelsListModel *model = [[TravelsListModel alloc] init];
            model.ID = [dic1 objectForKey:@"id"];
            [model setValuesForKeysWithDictionary:dic1];
            [_tableArray addObject:model];
            [model release];
        }
        [_tableView reloadData];
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TravelsListModel *model = [_tableArray objectAtIndex:indexPath.row];
    TravelsDetailViewController *travels = [[TravelsDetailViewController alloc] init];
    
    travels.ID = model.ID;
    travels.name = model.name;
    travels.first_day = model.first_day;
    travels.day_count = model.day_count;
    travels.travelsListModel = model;
    
    [self.navigationController pushViewController:travels animated:YES];
    [travels release];
 
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
